package com.example.facemanager.service;

import com.example.facemanager.config.ApiInfo;
import com.example.facemanager.config.Memory;
import com.example.facemanager.util.BaiduAlReturnMsgTrans;
import com.example.facemanager.util.GsonUtils;
import com.example.facemanager.util.HttpUtil;
import com.example.facemanager.util.PostRequestUtils;
import com.example.facemanager.vo.GroupInfoState;
import com.example.facemanager.vo.ReturnMsg;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author huchenying
 * @Date 2022/8/3 09:57
 * @Description
 */
@Service
@Slf4j
public class BaiduFaceManagerService {

    @Autowired
    private PostRequestUtils postRequestUtils;

    /**
     * @Author huchenying
     * @Date 2022/8/5 10:40
     * @Description 获取用户组列表
     */
    public ReturnMsg doGetUserGroupList() {
        if(Memory.getGroupInfoStates().size() != 0){
            return ReturnMsg.success(Memory.getGroupInfoStates());
        }
        // 请求url
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("start", 0);
            map.put("length", 100);

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = Memory.getAccess_token();

            String result = HttpUtil.post(ApiInfo.Query_USER_GROUP.getUrl(), accessToken, "application/json", param);
            System.out.println(result);
            ReturnMsg trans = BaiduAlReturnMsgTrans.trans(result);
            if(trans.getCode() == 400){
                return ReturnMsg.fail();
            }
            JSONObject jsonObject = new JSONObject(trans.getData().toString());
            JSONArray group_id_list = jsonObject.getJSONArray("group_id_list");
            List<GroupInfoState> res = new ArrayList<>();
            group_id_list.forEach(e -> {
                res.add(new GroupInfoState(e.toString()));
            });
            Memory.groupInfoStates = res;
            return ReturnMsg.success(Memory.getGroupInfoStates());
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMsg.fail();
        }
    }


    /**
     * @Author huchenying
     * @Date 2022/8/3 11:00
     * @Description 创建用户组
     */
    public ReturnMsg doAddUserGroup(String userGroupName) {
        log.debug("doAddUserGroup start param -> {}", userGroupName);
        Map<String, Object> param = new HashMap<>();
        param.put("group_id", userGroupName);
        String param2 = GsonUtils.toJson(param);
        String result = null;
        try {
            result = HttpUtil.post(ApiInfo.ADD_USER_GROUP.getUrl() , Memory.getAccess_token(), "application/json", param2);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            return ReturnMsg.fail();
        }
        ReturnMsg trans = BaiduAlReturnMsgTrans.trans(result);
        // 清空缓存
        if(trans.getCode() == 200){
            Memory.getGroupInfoStates().clear();
        }
        return trans;
    }

    /**
     * @Author huchenying
     * @Date 2022/8/3 11:00
     * @Description 删除用户组
     */
    public ReturnMsg doDeleteUserGroup(String userGroupName){
        log.debug("doDeleteUserGroup start param -> {}", userGroupName);
        Map<String, Object> param = new HashMap<>();
        param.put("group_id", userGroupName);
        String param2 = GsonUtils.toJson(param);
        String result = null;
        try {
            result = HttpUtil.post(ApiInfo.DELETE_USER_GROUP.getUrl(), Memory.getAccess_token(),"application/json", param2);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            return ReturnMsg.fail();
        }
        ReturnMsg trans = BaiduAlReturnMsgTrans.trans(result);
        if(trans.getCode() == 200){
            Memory.groupInfoStates.clear();
        }
        return trans;
    }

    /**
     * @Author huchenying
     * @Date 2022/8/3 11:00
     * @Description 添加用户数据(待优化)
     */
    public ReturnMsg doAddUser(String img, String userId, String groupId, String userName) {
        ReturnMsg returnMsg = doSearch(img, groupId);
        if(returnMsg.getCode() == 200){
            return ReturnMsg.success(returnMsg.getData());
        }

        log.info("doAddUser start param -> userId = {} , groupId = {} , userName = {}", userId, groupId, userName);
        Map<String, Object> param = new HashMap<>();
        param.put("image", img);
        param.put("image_type", "BASE64");
        param.put("user_id", userId);
        param.put("group_id", groupId);
        param.put("user_info", userName);
        Object o = postRequestUtils.postRequest(ApiInfo.ADD_USER.getUrl() + getTokenPart(), param);
        JSONObject result = new JSONObject(o);
        JSONObject body = result.getJSONObject("body");
        int error_code = body.getInt("error_code");
        if (error_code == 0) {
            return ReturnMsg.success();
        } else if (error_code == 223100) {
            return ReturnMsg.fail("用户已经存在");
        } else {
            return ReturnMsg.fail("添加失败");
        }
    }

    /**
     * @Author huchenying
     * @Date 2022/8/3 11:01
     * @Description 删除用户数据
     */
    @Deprecated
    public String doDeleteUser(String userId) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("log_id", "027d8308a2ec665acb1bdf63e513bcb9");
            map.put("user_id", "user1");
            map.put("group_id", "cba");
            map.put("face_token", "NORMAL");

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = Memory.getAccess_token();

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Author huchenying
     * @Date 2022/8/3 11:01
     * @Description 搜索用户
     */
    public ReturnMsg doSearch(String img, String groupId) {
        log.info("doSearch start param -> {}", groupId);
        Map<String, Object> param = new HashMap<>();
        param.put("image", img);
        param.put("image_type", "BASE64");
        param.put("group_id_list", groupId);
        Object o = postRequestUtils.postRequest(ApiInfo.SEARCH_USER.getUrl() + getTokenPart(), param);
        // 处理返回的数据
        if (o == null) {
            return ReturnMsg.fail();
        }
        JSONObject result = new JSONObject(o);
        JSONObject body = result.getJSONObject("body");

        int error_code = body.getInt("error_code");
        if (error_code == 0) {
            JSONObject data = body.getJSONObject("result");
            JSONArray user_list = data.getJSONArray("user_list");
            String userName = user_list.getJSONObject(0).getString("user_info");

            return ReturnMsg.success(userName);
        } else {
            return ReturnMsg.fail("陌生人，请联系管理员！");
        }
    }

    /**
     * @Author huchenying
     * @Date 2022/8/5 09:51
     * @Description 人脸更新
     */
    @Deprecated
    public ReturnMsg doUpdateUser() {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", "027d8308a2ec665acb1bdf63e513bcb9");
            map.put("group_id", "group_repeat");
            map.put("user_id", "user1");
            map.put("user_info", "cba");
            map.put("liveness_control", "NORMAL");
            map.put("image_type", "FACE_TOKEN");
            map.put("quality_control", "LOW");

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = Memory.getAccess_token();

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return ReturnMsg.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMsg.fail();
        }
    }

    /**
     * @Author huchenying
     * @Date 2022/8/5 10:37
     * @Description 获取用户列表
     */
    public ReturnMsg doGetUser(String groupId) {
        // 请求url
        try {
            Map<String, Object> map = new HashMap<>();
//            map.put("user_id", "user1");
            map.put("group_id", groupId);

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = Memory.getAccess_token();

            String result = HttpUtil.post(ApiInfo.GET_USER.getUrl(), accessToken, "application/json", param);
            System.out.println(result);
            return BaiduAlReturnMsgTrans.trans(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnMsg.fail();
        }
    }

    public String getTokenPart() {
        return "?" + "access_token=" + AuthService.getAuth();
    }

}
